package cn.fzkj.ws;

import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * @author mr
 * @description
 * @since 2024/2/20
 */
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse arg1, WebSocketHandler arg2,
        Map<String, Object> arg3) throws Exception {
        if (request instanceof ServletServerHttpRequest servletRequest) {
            HttpServletRequest httpRequest = servletRequest.getServletRequest();
            Map<String, String[]> parameterMap = httpRequest.getParameterMap();
            for (String paramKey : parameterMap.keySet()) {
                arg3.put(paramKey, httpRequest.getParameter(paramKey));
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Exception arg3) {
        log.info("afterHandshake...");
    }
}
